import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import { Modal } from 'antd'
import './index.less'
import LinkButton from '../link-button'
import memeryUtils from '../../utils/memeryUtils'
import storageUtils from '../../utils/storageUtils'
import menuList from '../../config/menuConfig'
import { getCurrentDate } from '../../utils/dateUtils'
import { reqWeather, reqAddress } from '../../api'

class Header extends Component {
  state = {
    city: '',
    time: getCurrentDate(Date.now()),
    dayPictureUrl: '',
    weather: ''
  }

  logout = () => {
    Modal.confirm({
      content: '确认退出吗？',
      onOk: () => {
        //确认退出
        storageUtils.removeUser()
        memeryUtils.user = {}
        this.props.history.replace('/login')
      }
    })
  }

  getWeather = async (city = '') => {
    const { dayPictureUrl, weather } = await reqWeather(city)
    this.setState({
      dayPictureUrl,
      weather
    })
  }

  //获取地点和天气
  getAddress = async () => {
    const { address: city } = await reqAddress()
    if (city) {
      this.setState({
        city
      })
      this.getWeather(city)
    } else {
      this.getWeather()
    }
  }

  getTitle = () => {
    const pathname = this.props.location.pathname
    let title
    menuList.forEach(item => {
      if (item.key === pathname) {
        title = item.title
      } else if (item.children) {
        const cItem = item.children.find(cItem => cItem.key === pathname)
        if (cItem) {
          title = cItem.title
        }
      }
    })
    return title
  }

  componentDidMount() {
    this.getAddress()

    this.timeID = setInterval(() => {
      this.setState({
        time: getCurrentDate(Date.now())
      })
    }, 1000)
  }

  componentWillUnmount() {
    clearInterval(this.timeID)
  }

  render() {
    const { city, time, dayPictureUrl, weather } = this.state
    const { username } = memeryUtils.user
    const title = this.getTitle()

    return (
      <div className="header">
        <div className="header-top">
          <span>欢迎，{username}</span>
          <LinkButton onClick={this.logout}>退出</LinkButton>
        </div>
        <div className="header-bottom">
          <div className="header-bottom-left">{title}</div>
          <div className="header-bottom-right">
            <span className="header-bottom-right-city">{city}</span>
            <span>{time}</span>
            <img src={dayPictureUrl} alt=""/>
            <span>{weather}</span>
          </div>
        </div>
      </div>
    )
  }
}

export default withRouter(Header)
